/* eslint-disable @typescript-eslint/no-unused-vars */
import { getMqttGoto, setMqttGoto } from "@/api/modules/system/system";
import PageHeader from "@/components/Frame/PageHeader";
import { GlobalStore } from "@/stores";
import { ElNotification, FormInstance, FormRules, UploadProps } from "element-plus";
import { confirm, showMsg, showTips } from "../../../utils/util";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
// import DataKeep from "../storageConfiguration/dataKeep";
import "./setting.scss";
//IP+PORT
let IpPortReg: RegExp =
	/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])$/;
//IP|域名 + PORT
IpPortReg = new RegExp(
	"^(([0-9]{1,3}.){3}[0-9]{1,3}" + // IP形式的URL- 199.194.52.184
		"|" + // 允许IP和DOMAIN（域名）
		"([0-9a-z_!~*'()-]+.)*" + // 域名- www.
		"([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]." + // 二级域名
		"[a-z]{2,6})" + // first level domain- .com or .museum
		"(:[0-9]{1,4})?" + // 端口- :80
		"((/?)|" + // a slash isn't required if there is no file name
		"(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
);
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const globalStore = GlobalStore();
		onMounted(() => {
			getUserLogo();
		});
		const getUserLogo = async () => {
			let res: any = getLogo();
			if (res.code == 200) {
				globalStore.setLogo(res.result.logo);
				globalStore.setHome(res.result.home);
				globalStore.setSystemName(res.result.systemName);
			}
		};
		return () => {
			return (
				<div class="setting-page">
					<PageHeader back={false} title={proxy?.$t("setting.title.tenant")} />
					{/* <div class="bg-white pt-8 pl-8 pr-8">
						<UserDomain />
					</div> */}
					<div class="bg-white p-8 mt-2">
						<SystemInfo />
					</div>
					<div class="bg-white p-8 mt-2">
						<ServerInfo />
					</div>
				</div>
			);
		};
	}
});

const ServerInfo = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const globalStore = GlobalStore();
		const publicStore = PublicStore();
		const state = reactive<any>({
			userInfo: publicStore.userInfo || {},
			conf: {
				dbInfo: {
					more: false,
					type: "postgres",
					server: "",
					authdb: "",
					db: "",
					username: publicStore.userInfo.username,
					password: ""
				},
				mqttInfo: {
					type: "cloud",
					server: "",
					username: "ssiot",
					password: "!@#abcd",
					more: false
				},
				portInfo: {
					min: 5000,
					max: 6000,
					total: 10
				},
				dbType: {
					cloud: {
						key: "cloud",
						label: "云端存储"
					},
					cust: {
						key: "cust",
						label: "数据库服务"
					}
				},
				mqttType: {
					cloud: {
						key: "cloud",
						label: "自定义"
					},
					cust: {
						key: "cust",
						label: "高级"
					}
				},
				dbList: {
					postgres: {
						label: "Postgres",
						icon: "",
						host: "ssiot.com",
						port: 5432,
						db: "sansan",
						username: "",
						password: ""
					},
					mysql: {
						label: "MySQL",
						icon: "",
						host: "",
						port: 5432,
						db: "sansan",
						username: "",
						password: ""
					},
					mongo: {
						label: "Mongo",
						icon: "",
						host: "",
						port: 5432,
						db: "sansan",
						username: "",
						password: ""
					}
				}
			}
		});
		const dbtype = {
			postgres: { type: "postgres", label: "Postgres" },
			mysql: { type: "mysql", label: "Mysql" },
			mongo: { type: "mongo", label: "MongoDB" },
			Kafka: { type: "Kafka", label: "Kafka" }
		};
		watch(
			() => state.conf.dbInfo.dbType,
			() => {
				state.conf.dbInfo.host = state.conf.dbInfo.host || "127.0.0.1";
				switch (state.conf.dbInfo.dbType) {
					case dbtype.postgres.type:
						state.conf.dbInfo.port = 5432;
						break;
					case dbtype.mysql.type:
						state.conf.dbInfo.port = 3306;
						break;
					case dbtype.mongo.type:
						state.conf.dbInfo.port = 27017;
						state.conf.dbInfo.authdb = state.conf.dbInfo.authdb || "admin";
						break;
					case dbtype.Kafka.type:
						state.conf.dbInfo.port = 9092;
						break;
				}
			}
		);
		const ipPort = (rule: any, value: any, callback: any) => {
			if (value) {
				if (IpPortReg.test(value) == false) {
					callback(new Error("请输入有效地址（127.0.0.1:1883）"));
					return;
				}
				callback();
			} else {
				callback();
			}
		};
		const server = ref();
		const mqttFormRef = ref<FormInstance>();
		const mqttFormRules = reactive<FormRules>({
			goto: [{ validator: ipPort, trigger: "blur" }]
		});
		onMounted(async () => {
			let { result } = await getMqttGoto();
			publicStore.userInfo.goto = result as string;
			state.conf.mqttInfo.server = result || "";
			server.value = `${window.location.hostname}:9010`;
		});

		const saveGotoAddress = () => {
			if (state.userInfo.goto == state.conf.mqttInfo.server) {
				showMsg("无任何内容修改", false);
				return;
			}
			state.userInfo.goto = state.conf.mqttInfo.server == server.value ? "" : state.conf.mqttInfo.server;
			mqttFormRef.value?.validate((valid: any) => {
				if (!valid) {
					return;
				}

				confirm({ content: state.userInfo.goto ? "确定应用自定义接入配置？" : "确定删除自定义接入配置？" }).then(async flag => {
					if (!flag) {
						return;
					}
					let { code, message } = await setMqttGoto({ goto: state.userInfo.goto });
					state.conf.mqttInfo.server = state.userInfo.goto;
					showTips(code, "修改自定义接入配置", message);
				});
			});
		};
		return () => {
			return (
				<>
					{/* <DataKeep></DataKeep> */}

					<div class="bg-white pl-8">
						<div class="block-title border-bottom">
							<span>{proxy?.$t("setting.card_title.dev_access")}</span>
							{/* <el-link type="primary" link onClick={() => {}}>
								测试连接
							</el-link> */}
						</div>
						<div class="p-4 mt-4 flex">
							<div class="edit-form">
								<el-form label-width="100px" ref={mqttFormRef} model={state.userInfo} rules={mqttFormRules}>
									<el-form-item label={proxy?.$t("setting.form_label.server")}>
										<el-input v-model={server.value} placeholder={proxy?.$t("setting.placeholder.server")} disabled>
											{{
												append: () => {
													return <el-link class="iconfont iconbx-copy-alt" v-copy={state.conf.mqttInfo.server}></el-link>;
												}
											}}
										</el-input>
									</el-form-item>
									<div class="relative">
										{!state.userInfo.goto ? (
											<>
												{/* <el-form-item label="Client ID">
													<el-input v-model={state.conf.mqttInfo.clientId} placeholder="客户端ID">
														{{
															append: () => {
																return state.conf.mqttInfo.clientId ? null : (
																	<el-button type="primary" link onClick={() => (state.conf.mqttInfo.clientId = generateUUID())}>
																		<span class="text-sm p-1 pr-1">自动生成</span>
																	</el-button>
																);
															}
														}}
													</el-input>
												</el-form-item> */}
												<el-form-item label={proxy?.$t("setting.form_label.username")}>
													<el-input
														v-model={state.conf.mqttInfo.username}
														placeholder={proxy?.$t("setting.placeholder.username")}
														disabled
													/>
												</el-form-item>
												<el-form-item label={proxy?.$t("setting.form_label.password")}>
													<el-input
														v-model={state.conf.mqttInfo.password}
														placeholder={proxy?.$t("setting.placeholder.password")}
														disabled
													/>
												</el-form-item>
											</>
										) : null}
									</div>
									{/* <el-form-item label={proxy?.$t("setting.form_label.goto")} prop="goto">
										<el-input v-model={state.conf.mqttInfo.server} placeholder={proxy?.$t("setting.placeholder.goto")}>
											{{
												append: () => {
													return <el-link class="iconfont iconbx-copy-alt" v-copy={state.conf.mqttInfo.server}></el-link>;
												}
											}}
										</el-input>
										<div class="text-gray-400">{proxy?.$t("setting.tips")}</div>
									</el-form-item> */}

									<el-form-item>
										<el-button type="primary" onClick={saveGotoAddress}>
											{proxy?.$t("setting.btn.save")}
										</el-button>
										{/* <el-link class="ml-8" type="primary" onClick={() => (state.conf.mqttInfo.more = !state.conf.mqttInfo.more)}>
											{state.conf.mqttInfo.more ? "更少" : "更多"}
											<i class={`iconfont ${state.conf.mqttInfo.more ? "iconchevrons-up" : "iconchevrons-down"}`}></i>
										</el-link> */}
									</el-form-item>
								</el-form>
							</div>
							<div class="tips text-sm">
								<div class="master-msg">{proxy?.$t("setting.msg")}</div>
							</div>
						</div>
					</div>
					{false ? (
						<>
							<div class="bg-white pl-8 pr-8 pt-2 mt-4">
								<div class="block-title border-bottom">应用参数</div>
								<div class="p-4 mt-4">
									<el-form label-width="100px">
										<el-form-item label="端口范围">
											<div class="flex">
												<el-input v-model={state.conf.portInfo.min} placeholder="起始" />
												<span class="pl-2 pr-2">~</span>
												<el-input v-model={state.conf.portInfo.max} placeholder="起始" />
											</div>
										</el-form-item>
									</el-form>
								</div>
							</div>

							<div class="bg-white pl-8 pr-8 pt-2 mt-4">
								<div class="block-title border-bottom">
									<span>存储服务</span>
									<el-link type="primary" link onClick={() => {}}>
										测试连接
									</el-link>
								</div>
								<div class="p-4 mt-4 flex">
									<div class="edit-form">
										<el-form label-width="100px">
											<el-form-item label="数据库类型">
												<el-select v-model={state.conf.dbInfo.dbType}>
													{Object.values(dbtype).map(item => {
														return <el-option label={item.label} value={item.type}></el-option>;
													})}
												</el-select>
											</el-form-item>
											<el-form-item label="主机">
												<el-input v-model={state.conf.dbInfo.host} placeholder="连接主机" />
											</el-form-item>
											<el-form-item label="端口">
												<el-input v-model={state.conf.dbInfo.port} placeholder="连接端口" />
											</el-form-item>

											<div class="relative">
												{state.conf.dbInfo.more ? (
													<>
														{state.conf.dbInfo.dbType == dbtype.mongo ? (
															<>
																<el-form-item label="认证方式">
																	<el-select v-model={state.conf.dbInfo.dbType}>
																		<el-option label="匿名认证" value=""></el-option>
																		<el-option label="账号密码" value="password"></el-option>
																	</el-select>
																</el-form-item>
																<el-form-item label="验证数据库">
																	<el-input v-model={state.conf.dbInfo.authdb} placeholder="验证数据库" />
																</el-form-item>
															</>
														) : null}
														<el-form-item label="数据库">
															<el-input v-model={state.conf.dbInfo.db} placeholder="数据库名称" />
														</el-form-item>
														<el-form-item label="用户名">
															<el-input v-model={state.conf.dbInfo.username} placeholder="连接用户名" />
														</el-form-item>
														<el-form-item label="密码">
															<el-input v-model={state.conf.dbInfo.password} type="password" placeholder="连接密码" />
														</el-form-item>
													</>
												) : null}
											</div>
											<el-form-item>
												<el-button type="primary">保存</el-button>
												<el-link class="ml-8" type="primary" onClick={() => (state.conf.dbInfo.more = !state.conf.dbInfo.more)}>
													{state.conf.dbInfo.more ? "更少" : "更多"}
													<i class={`iconfont ${state.conf.dbInfo.more ? "iconchevrons-up" : "iconchevrons-down"}`}></i>
												</el-link>
											</el-form-item>
										</el-form>
									</div>
									<div class="tips">
										<div class="master-msg"></div>
										<div class="descript-msg">{proxy?.$t("setting.tips")}</div>
									</div>
								</div>
							</div>
						</>
					) : null}
				</>
			);
		};
	}
});

import { getLogo, saveLogo } from "@/api/modules/user";
import logo from "@/assets/images/logo.png";
import { SYSTEM_ID } from "@/config/config";
import { filePrefix } from "@/hooks/useSystem";
import { PublicStore } from "@/stores/modules/public";
import { openWin } from "@/utils/routerUtil";
const SystemInfo = defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const globalStore = GlobalStore();
		const publicStore = PublicStore();
		const custForm = reactive({
			systemName: globalStore.setting.systemName,
			logo: globalStore.setting.logo,
			home: globalStore.setting.home
		});
		const uploadSuccess = (res: any) => {
			custForm.logo = res.result;
		};
		const isDisabled = ref(publicStore.userInfo.creatorId != "1");
		const clickSave = async () => {
			custForm.logo = !custForm.logo || custForm.logo == logo ? "" : custForm.logo;
			let { code, message } = await saveLogo(custForm);
			let ok = showTips(code, "个性化设置", message);
			if (ok) {
				globalStore.setLogo(custForm.logo);
				globalStore.setSystemName(custForm.systemName);
			}
		};
		let logoInfo = {
			size: 100,
			unit: "kb"
		};
		/* @description 文件上传之前判断
		 * @param rawFile 上传的文件
		 * */
		const beforeUpload: UploadProps["beforeUpload"] = rawFile => {
			const imgSize = rawFile.size / 1024 < logoInfo.size;
			if (!imgSize)
				ElNotification({
					title: "温馨提示",
					message: `Logo图片大小不能超过 ${logoInfo.size}${logoInfo.unit}！`,
					type: "warning"
				});
			return imgSize;
		};
		return () => {
			return (
				<div class="bg-white pl-8 pr-8">
					<div class="block-title border-bottom">
						<span>{proxy?.$t("setting.card_title.personalize")}</span>
					</div>
					<div class="p-4 mt-2 ">
						<el-form label-width="120px" size="large" class="pt-3">
							<el-form-item label={proxy?.$t("setting.form_label.systemname")}>
								<div class="flex w-full">
									<el-input v-model={custForm.systemName} class="flex-1" />
									<el-upload
										show-file-list={false}
										before-upload={beforeUpload}
										on-success={uploadSuccess}
										headers={{
											Authentication: publicStore.token,
											systemid: SYSTEM_ID,
											timestamp: Date.now()
										}}
										action="/api/file/upload"
									>
										<el-button type="primary" plain disabled={isDisabled.value}>
											{proxy?.$t("setting.btn.upload")}
										</el-button>
									</el-upload>
								</div>
							</el-form-item>
							<el-form-item label={proxy?.$t("setting.form_label.preview")} class="preview">
								<div class="system-title-preview flex pl-5">
									<el-image src={!custForm.logo || custForm.logo == logo ? logo : `${filePrefix()}${custForm.logo}`}></el-image>
									<div class="title ">{custForm.systemName}</div>
								</div>
								<div class="pt-2">
									<el-button type="primary" plain size="default" disabled={isDisabled.value} onClick={clickSave}>
										{proxy?.$t("setting.btn.confirm")}
									</el-button>
									<el-button
										size="default"
										disabled={isDisabled.value}
										onClick={() => {
											globalStore.setLogo("");
											globalStore.setSystemName("");
											custForm.systemName = globalStore.setting.systemName;
											custForm.logo = globalStore.setting.logo;
											clickSave();
										}}
									>
										{proxy?.$t("common.btn.reset")}
									</el-button>
								</div>
							</el-form-item>
							<el-form-item label={proxy?.$t("setting.form_label.content")}>
								<div class="text-gray-500 leading-6 pt-1">
									<div>{proxy?.$t("setting.tips.tip1")}</div>
									<div>{proxy?.$t("setting.tips.tip2")}</div>
									<div>{proxy?.$t("setting.tips.tip3")}</div>
									<div>
										{proxy?.$t("setting.tips.tip4")}
										{logoInfo.size}
										{logoInfo.unit}
									</div>
								</div>
							</el-form-item>
						</el-form>
					</div>
				</div>
			);
		};
	}
});

const UserDomain = defineComponent({
	setup() {
		const globalStore = GlobalStore();
		const publicStore = PublicStore();
		const state = reactive<any>({
			home: globalStore.setting.home
		});
		const save = async () => {
			if (state.home && !state.home.startsWith("http")) {
				state.home = "http://" + state.home;
			}
			let { code, message } = await saveLogo({
				systemName: globalStore.setting.systemName,
				logo: globalStore.setting.logo,
				home: state.home
			});
			let ok = showTips(code, "个性化设置", message);
			if (ok) {
				globalStore.setHome(state.home);
			}
		};
		const gotoPage = () => {
			let token = "";
			if (RegExp(/\?.+=.*/).test(globalStore.setting.home)) {
				token = `&token=${publicStore.token}`;
			} else {
				token = `/#/?token=${publicStore.token}`;
			}
			openWin(globalStore.setting.home + token);
		};
		return () => {
			return (
				<>
					<div class="bg-white pl-8 pr-8 pt-2">
						<div class="block-title border-bottom">
							<span>用户空间</span>
						</div>
						<div class="p-4 mt-2 ">
							<el-alert closable={false} type="error">
								警告：默认主页配置错误，会导致系统无法使用，请确保地址能正常访问。
							</el-alert>
							<el-form label-width="120px" class="pt-3">
								<el-form-item label="默认主页">
									<el-input v-model={state.home} placeholder="http://ssiot.cc:9000">
										{{
											append: () => {
												return globalStore.setting.home ? (
													<el-link type="primary" onClick={gotoPage}>
														访问
													</el-link>
												) : null;
											}
										}}
									</el-input>
								</el-form-item>

								<el-form-item>
									<el-button type="primary" onClick={save}>
										保存
									</el-button>
								</el-form-item>
							</el-form>
						</div>
					</div>
				</>
			);
		};
	}
});
